package com.jydd.plug_in_study.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * created by 韦敏敏
 * on 2019/12/25
 */
public class Util {
    private static final String TAG = "liaoming";
    private static final int BYTE_BUF_SIZE = 2048;
    public static void log(String msg){
        Log.d(TAG, msg);
    }
    public static void showToast(Context context, String msg){
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }
    public static void copyAsset(Context context, String assetName, String targetName, AssetFileCopyResult assetFileCopyResult) throws IOException {
        Util.log("creating file " + targetName + " from " + assetName);
        File targetFile = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            AssetManager assets = context.getAssets();
            targetFile = new File(targetName);
            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            if(!targetFile.exists()){
                targetFile.createNewFile();
            }
            inputStream = assets.open(assetName);
            Util.log("Creating outputstream");
            outputStream = new FileOutputStream(targetFile, false);
            copy(inputStream, outputStream,assetFileCopyResult);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(outputStream != null) {
                outputStream.close();
                outputStream.flush();
            }
            if(inputStream != null)
                inputStream.close();
        }
    }
    public interface AssetFileCopyResult{
        void done();
    }
    private static void copy(InputStream from, FileOutputStream to, AssetFileCopyResult assetFileCopyResult) throws IOException {
        byte[] buf = new byte[BYTE_BUF_SIZE];
        while(true){
            int r = from.read(buf);
            if(r == -1) {
                assetFileCopyResult.done();
                break;
            }
            to.write(buf, 0, r);
            Util.log("asset, buf-write :" + buf.toString());
        }
    }
}
